<?php

namespace App\Kuafu\Export\Service\ExportFactory;

use App\Kuafu\Export\Model\ExportDownloadModel;
use App\Kuafu\Statistics\Service\StatisticsService;
use Illuminate\Support\Str;

/**
 * app-堂食订单明细
 */
class ExportWebInOrderService extends BaseExportService
{
    private string $localPath = '';

    public function query(): self
    {
        $shopIds         = ($this->params['shopIds'] ?? []);
        $startAt         = date('Y-m-d H:i:s', $this->params['showStartAt'] ?? time());
        $endAt           = date('Y-m-d H:i:s', $this->params['showEndAt'] ?? time());
        $this->localPath = sys_get_temp_dir() . '/' . Str::random();

        self::streamExport($shopIds, $startAt, $endAt, $this->localPath);

        return $this;
    }

    public function path(): string
    {
        return $this->upload($this->localPath);
    }

    public static function streamExport(array $shopIds, string $startAt, string $endAt, string $path)
    {
        $data = [];

        $shopId = 0;
        foreach ($shopIds as $shopKey => $shopId) {

            $shopData = StatisticsService::shopOrderExcel($shopId, 0, 0, $startAt, $endAt, '', false);

            // 合并每家门店的数据
            for ($i = 0; $i < count($shopData); $i++) {

                // 初始化
                if (!isset($data[$i]['rows'])) {
                    $data[$i]['rows']  = [];
                    $data[$i]['info']  = [];
                    $data[$i]['title'] = $shopData[$i]['title'];
                }

                // 把yield转成数组
                if ($shopData[$i]['rows'] instanceof \Generator) {
                    $shopData[$i]['rows'] = iterator_to_array($shopData[$i]['rows']);
                }

                // 合并
                if ($shopKey > 0) {
                    unset($shopData[$i]['rows'][0]);
                }
                $data[$i]['rows'] = array_merge($data[$i]['rows'], $shopData[$i]['rows']);
            }
        }

        // 排序
        $data = collect($data)->map(function ($item, $k) {
            if ($k == 0) {
                $item['rows'] = collect($item['rows'])->sortByDesc(6)->values()->toArray();
                return $item;
            }

            if ($k == 2) {
                $item['rows'] = collect($item['rows'])->sortByDesc(6)->values()->toArray();
                return $item;
            }

            return $item;
        })->toArray();

        // 生成excel
        $fileType = ExportDownloadModel::FILE_TYPE_WEB_IN_ORDER;
        $client   = ExportDownloadModel::CLIENT_TYPE_WEB;
        $fileName = (new ExportDownloadModel())->buildFileName($shopId, strtotime($startAt), strtotime($endAt), $fileType, $client);
        StatisticsService::spreadsheetExcel($data, $fileName, $path);

        return $data;
    }
}
